package ddz.logic.login;

import com.kaka.notice.annotation.Handler;
import com.kaka.util.Charsets;
import com.kaka.util.StringUtils;
import ddz.constants.Crypto;
import ddz.constants.ErrCode;
import ddz.constants.ErrLevel;
import ddz.constants.OpCode;
import ddz.net.CtxManager;
import ddz.net.LogicDataHandler;
import ddz.net.ProtocolMessage;
import ddz.protos.Login;
import ddz.utils.DES;

@Handler(cmd = OpCode.cmd_rebind)
public class RebindHandler extends LogicDataHandler {
    @Override
    protected void execute(ProtocolMessage msg) throws Exception {
        byte[] bytes = (byte[]) msg.getBody();
        Login.CsRebind csRebind = Login.CsRebind.parseFrom(bytes);
        String token = csRebind.getToken();
        byte[] tokenBytes;
        try {
            tokenBytes = StringUtils.decodeHexToByte(token);
            tokenBytes = DES.decrypt(tokenBytes, Crypto.LOGIN_TOKEN_DES_KEY_BYTES);
        } catch (Exception ex) {
            sendError(msg.ctx(), opcode(), ErrLevel.ERROR, ErrCode.login_token_invalid);
            return;
        }
        if (tokenBytes == null) return;
        token = new String(tokenBytes, Charsets.utf8);
        String[] parts = token.split(":");
        long uid = Long.parseLong(parts[0]);
        long validity = Long.parseLong(parts[1]);
        if (validity < System.currentTimeMillis()) {
            sendError(msg.ctx(), opcode(), ErrLevel.ERROR, ErrCode.login_token_invalid);
            return;
        }
        CtxManager ctxManager = CtxManager.instance();
        ctxManager.add(uid, msg.ctx());
    }
}
